package com.zt.proxy.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.constraints.NotNull;

import com.zt.proxy.model.PointModel;

public class StringUtil {

    /**
     * 分割URL的正则表达式
     */
    private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)");
    
	/**
	 * 简单格式化{}样式的字符串.<br>
	 * String str = "aaa{} bbb{} ccc{}";<br>
	 * System.out.println(StringUtil.format(str, "1", "2", "3"));
	 * @param src 源字符串
	 * @param param 跟源字符串{}匹配的个数字符串
	 * @return
	 */
	public static String format(String src, Object... param) {
		int i = 0;
		int index = 0;
		StringBuffer sb = new StringBuffer(src);
		while (-1 != (index = sb.indexOf("{}"))) {
			sb.replace(index, index + 2, String.valueOf(param[i++]));
		}
		return sb.toString();
	}
	
    public static Map<String, String> parseKeyValuePair(String str, String itemSeparator) {
        String[] tmp = str.split(itemSeparator);
        Map<String, String> map = new HashMap<>(tmp.length);
        for (int i = 0; i < tmp.length; i++) {
            Matcher matcher = KVP_PATTERN.matcher(tmp[i]);
            if (matcher.matches() == false) {
                continue;
            }
            map.put(matcher.group(1), matcher.group(2));
        }
        return map;
    }
    
    /**
     * parse ip and port from the conn.
     *
     * @param conn
     * @return
     */
    public static PointModel parsePointModel(@NotNull String conn) {

        // split host and port
        String[] pairs = conn.replace("：", ":").split(":");
        String host = pairs[0];
        String port = pairs[1];

        return new PointModel(host, Integer.valueOf(port));
    }

}
